package com.lzl.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.lzl.common_utils.R;
import com.lzl.servicebase.exceptionHandler.LZLException;
import com.lzl.vod.service.VodService;
import com.lzl.vod.utils.ConstantVodUtils;
import com.lzl.vod.utils.InitVodClient;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
//@CrossOrigin
public class VodController {

    @Autowired
    private VodService vodService;

    /**
     * 上传视频到阿里云
     * 上传的方法都是post提交
     *
     * @param file
     * @return
     */
    @PostMapping("uploadVideo")
    public R uploadVideoToALiYun(MultipartFile file) {

        String videoId = vodService.uploadVideo(file);

        //需要返回 视频的id 然后添加到数据库
        return R.ok().data("videoId", videoId);
    }

    //根据视频id 删除阿里云视频
    @DeleteMapping("deleteAlyVideo/{id}")
    public R deleteAlyVideo(@PathVariable String id) {
        vodService.deleteAlyVideoById(id);
        return R.ok();
    }

    //删除多个阿里云视频
    @DeleteMapping("deleteBatch")
    public R deleteBatch(@RequestParam("videoIdList") List<String> videoIdList) {
        vodService.removeMoreAlyVideo(videoIdList);

        return R.ok();
    }

    //根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public R getplayAuth(@PathVariable String id) {

        try {
            //创建初始化对象---之前写过该工具类
            DefaultAcsClient client =
                    InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建获取凭证的对象--request和response
            GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();

            //向request设置视频的id
            request.setVideoId(id);

            //调用方法得到凭证
            response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();

            return R.ok().data("playAuth", playAuth);

        } catch (Exception e) {
           throw new LZLException(20001,"获取对应视频凭证");
        }
    }

}
